﻿<template>
  <div class="register-manage-container">
    <h2 class="page-title">挂号订单管理</h2>
    
    <!-- 筛选区域 -->
    <div class="filter-section">
      <div class="filter-item">
        <el-input 
          v-model="queryParams.searchKey" 
          placeholder="输入订单号或用户名" 
          clearable 
          @keyup.enter="handleQuery"
        />
      </div>
      <div class="filter-item">
        <span class="label">日期</span>
        <el-date-picker
          v-model="queryParams.startTime"
          type="datetime"
          placeholder="开始时间"
          value-format="YYYY-MM-DD HH:mm:ss"
          clearable
        />
      </div>
      <div class="filter-item">
        <el-date-picker
          v-model="queryParams.endTime"
          type="datetime"
          placeholder="结束时间"
          value-format="YYYY-MM-DD HH:mm:ss"
          clearable
        />
      </div>
      <div class="filter-item">
        <el-button type="primary" @click="handleQuery">筛选</el-button>
      </div>
    </div>
    
    <!-- 数据表格 -->
    <div class="table-section">
      <!-- 标签页 -->
      <div class="tabs">
        <div 
          v-for="(tab, index) in tabs" 
          :key="index" 
          :class="['tab-item', {'active': queryParams.orderStatus === tab.value}]"
          @click="handleTabChange(tab.value)"
        >
          {{ tab.label }}
        </div>
      </div>
      
      <!-- 表格 -->
      <el-table
        v-loading="loading"
        :data="registerList"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column prop="orderNo" label="订单编号" align="center" />
        <el-table-column label="提交时间" align="center">
          <template #default="scope">
            {{ formatDateTime(scope.row.submitTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="userName" label="用户名" align="center" />
        <el-table-column prop="doctor" label="医生" align="center" />
        <el-table-column prop="department" label="科室" align="center" />
        <el-table-column label="挂号费" align="center">
          <template #default="scope">
            {{ scope.row.registrationFee }} 元
          </template>
        </el-table-column>
        <el-table-column label="订单状态" align="center">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.orderStatus)">
              {{ getStatusText(scope.row.orderStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="120">
          <template #default="scope">
            <el-button type="primary" link @click="handleView(scope.row)">查看订单</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageIndex"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    
    <!-- 查看订单对话框 -->
    <el-dialog v-model="dialogVisible" :title="getDetailTitle()" width="700px" destroy-on-close>
      <div v-if="orderDetail" class="order-detail">
        <!-- 挂号信息区域 -->
        <div class="detail-section">
          <h3 class="section-title">挂号信息</h3>
          <div class="detail-grid">
            <div class="detail-item">
              <span class="label">就诊时间：</span>
              <span>{{ formatDateTime(orderDetail.registrationInfo?.appointmentTime) }}</span>
            </div>
            <div class="detail-item">
              <span class="label">就诊医院：</span>
              <span>{{ orderDetail.registrationInfo?.hospital }}</span>
            </div>
            <div class="detail-item">
              <span class="label">科室：</span>
              <span>{{ orderDetail.registrationInfo?.department }}</span>
            </div>
            <div class="detail-item">
              <span class="label">医生：</span>
              <span>{{ orderDetail.registrationInfo?.doctor }}</span>
            </div>
            <div class="detail-item">
              <span class="label">医生职称：</span>
              <span>{{ orderDetail.registrationInfo?.doctorTitle }}</span>
            </div>
            <div class="detail-item">
              <span class="label">医事服务费：</span>
              <span>￥{{ orderDetail.registrationInfo?.registrationFee }}</span>
            </div>
            <div class="detail-item">
              <span class="label">挂号单号：</span>
              <span>{{ orderDetail.registrationInfo?.registrationNo }}</span>
            </div>
          </div>
        </div>

        <!-- 订单信息区域 -->
        <div class="detail-section">
          <h3 class="section-title">订单信息</h3>
          <div class="detail-grid">
            <div class="detail-item">
              <span class="label">订单编号：</span>
              <span>{{ orderDetail.orderInfo?.orderNo }}</span>
            </div>
            <div class="detail-item">
              <span class="label">状态：</span>
              <span>{{ getStatusText(orderDetail.orderInfo?.status) }}</span>
            </div>
            <div class="detail-item">
              <span class="label">应付金额：</span>
              <span>￥{{ orderDetail.orderInfo?.payableAmount }}</span>
            </div>
            <div class="detail-item">
              <span class="label">优惠券：</span>
              <span>￥{{ orderDetail.orderInfo?.couponAmount }}</span>
            </div>
            <div class="detail-item">
              <span class="label">实际支付：</span>
              <span>￥{{ orderDetail.orderInfo?.actualPayment }}</span>
            </div>
            <div class="detail-item">
              <span class="label">创建时间：</span>
              <span>{{ formatDateTime(orderDetail.orderInfo?.createTime) }}</span>
            </div>
            
            <!-- 已完成或已退款状态才显示支付方式和支付时间 -->
            <template v-if="orderDetail.orderInfo?.status === '已完成' || orderDetail.orderInfo?.status === '2' || orderDetail.orderInfo?.status === '已退款' || orderDetail.orderInfo?.status === '4'">
              <div class="detail-item">
                <span class="label">支付方式：</span>
                <span>{{ orderDetail.orderInfo?.paymentMethod }}</span>
              </div>
              <div class="detail-item">
                <span class="label">支付时间：</span>
                <span>{{ formatDateTime(orderDetail.orderInfo?.paymentTime) }}</span>
              </div>
            </template>
            
            <!-- 已退款状态才显示退款金额和退款时间 -->
            <template v-if="orderDetail.orderInfo?.status === '已退款' || orderDetail.orderInfo?.status === '4'">
              <div class="detail-item">
                <span class="label">退款金额：</span>
                <span>￥{{ orderDetail.orderInfo?.refundAmount }}</span>
              </div>
              <div class="detail-item">
                <span class="label">退款时间：</span>
                <span>{{ formatDateTime(orderDetail.orderInfo?.refundTime) }}</span>
              </div>
            </template>
          </div>
        </div>

        <!-- 就诊人信息区域 -->
        <div class="detail-section">
          <h3 class="section-title">就诊人信息</h3>
          <div class="detail-grid">
            <div class="detail-item">
              <span class="label">姓名：</span>
              <span>{{ orderDetail.patientInfo?.name }}</span>
            </div>
            <div class="detail-item">
              <span class="label">性别：</span>
              <span>{{ orderDetail.patientInfo?.gender }}</span>
            </div>
            <div class="detail-item">
              <span class="label">年龄：</span>
              <span>{{ orderDetail.patientInfo?.age }}</span>
            </div>
            <div class="detail-item">
              <span class="label">联系电话：</span>
              <span>{{ orderDetail.patientInfo?.phone }}</span>
            </div>
          </div>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">返回</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { axiosrzsh } from '@/http/axiosRead'

// 定义挂号订单的接口类型
interface RegistrationOrder {
  orderNo: string
  submitTime: string
  userName: string
  doctor: string
  department: string
  registrationFee: number
  orderStatus: string
}

// 定义订单详情的接口类型
interface RegistrationInfo {
  appointmentTime: string
  hospital: string
  department: string
  doctor: string
  doctorTitle: string
  registrationFee: number
  registrationNo: string
}

interface OrderInfo {
  orderNo: string
  status: string
  payableAmount: number
  couponAmount: number
  actualPayment: number
  createTime: string
  paymentMethod?: string
  paymentTime?: string
  refundAmount?: number
  refundTime?: string
}

interface PatientInfo {
  name: string
  gender: string
  age: number
  phone: string
}

interface OrderDetail {
  registrationInfo?: RegistrationInfo
  orderInfo?: OrderInfo
  patientInfo?: PatientInfo
}

// 定义查询参数
const queryParams = reactive({
  searchKey: '',
  startTime: '',
  endTime: '',
  orderStatus: '0', // 默认查询全部
  pageIndex: 1,
  pageSize: 10
})

// 标签页配置
const tabs = [
  { label: '全部', value: '0' },
  { label: '待支付', value: '1' },
  { label: '已完成', value: '2' },
  { label: '已取消', value: '3' },
  { label: '已退款', value: '4' }
]

// 数据列表
const registerList = ref<RegistrationOrder[]>([])
const total = ref(0)
const loading = ref(false)
const dialogVisible = ref(false)
const orderDetail = ref<OrderDetail | null>(null)

// 获取挂号订单列表
const getRegisterList = async () => {
  loading.value = true
  try {
    const response = await axiosrzsh.get('/RegistrationOrder', {
      params: queryParams
    })
    if (response.data.code === 200) {
      registerList.value = response.data.pageData || []
      total.value = response.data.totaCount || 0
    } else {
      ElMessage.error(response.data.msg || '获取数据失败')
    }
  } catch (error) {
    console.error('获取挂号订单数据失败:', error)
    ElMessage.error('获取数据失败，请检查网络连接')
  } finally {
    loading.value = false
  }
}

// 获取详情页面标题
const getDetailTitle = (): string => {
  if (!orderDetail.value || !orderDetail.value.orderInfo) {
    return '挂号订单详情'
  }
  
  const status = orderDetail.value.orderInfo.status
  if (status === '待支付' || status === '1') return '订单详情-待支付'
  if (status === '已完成' || status === '2') return '订单详情-已完成'
  if (status === '已取消' || status === '3') return '订单详情-已取消'
  if (status === '已退款' || status === '4') return '订单详情-已退款'
  
  return '挂号订单详情'
}

// 获取状态显示文本
const getStatusText = (status: string | undefined): string => {
  if (!status) return ''
  if (status === '1' || status === '待支付') return '待支付'
  if (status === '2' || status === '已完成') return '已完成'
  if (status === '3' || status === '已取消') return '已取消'
  if (status === '4' || status === '已退款') return '已退款'
  return status
}

// 获取状态显示类型
const getStatusType = (status: string | undefined): string => {
  if (!status) return 'info'
  if (status === '1' || status === '待支付') return 'warning'
  if (status === '2' || status === '已完成') return 'success'
  if (status === '3' || status === '已取消') return 'info'
  if (status === '4' || status === '已退款') return 'danger'
  return 'info'
}

// 格式化日期时间
const formatDateTime = (dateTimeStr: string | undefined): string => {
  if (!dateTimeStr) return '-'
  const date = new Date(dateTimeStr)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`
}

// 处理查询
const handleQuery = () => {
  queryParams.pageIndex = 1
  getRegisterList()
}

// 处理标签页切换
const handleTabChange = (status: string) => {
  queryParams.orderStatus = status
  handleQuery()
}

// 处理分页大小改变
const handleSizeChange = (size: number) => {
  queryParams.pageSize = size
  getRegisterList()
}

// 处理分页页码改变
const handleCurrentChange = (page: number) => {
  queryParams.pageIndex = page
  getRegisterList()
}

// 处理查看详情
const handleView = async (row: RegistrationOrder) => {
  try {
    // 使用订单号获取详情
    const response = await axiosrzsh.get(`/RegistrationOrder/${row.orderNo}`)
    
    if (response.data.code === 200) {
      orderDetail.value = response.data.data
      dialogVisible.value = true
    } else {
      ElMessage.error(response.data.msg || '获取订单详情失败')
    }
  } catch (error) {
    console.error('获取订单详情失败:', error)
    ElMessage.error('获取订单详情失败，请检查网络连接')
  }
}

// 页面加载时获取数据
onMounted(() => {
  getRegisterList()
})
</script>

<style scoped>
.register-manage-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 5px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.page-title {
  font-size: 22px;
  font-weight: bold;
  margin-bottom: 20px;
  color: #333;
}

.filter-section {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f7f7f7;
  border-radius: 5px;
}

.filter-item {
  margin-right: 15px;
  margin-bottom: 10px;
}

.filter-item .label {
  margin-right: 8px;
}

.tabs {
  display: flex;
  border-bottom: 1px solid #eee;
  margin-bottom: 20px;
}

.tab-item {
  padding: 10px 20px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
  border-bottom: 2px solid transparent;
}

.tab-item.active {
  color: #409EFF;
  border-bottom: 2px solid #409EFF;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.order-detail {
  padding: 10px 0;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eaeaea;
}

.detail-section {
  margin-bottom: 20px;
  background-color: #f9f9f9;
  border-radius: 5px;
  padding: 15px;
}

.detail-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
}

.detail-item {
  line-height: 24px;
}

.detail-item .label {
  font-weight: bold;
  margin-right: 10px;
  color: #606266;
}
</style>
